package com.tenebrous.jestic.chain;

import com.alibaba.fastjson.JSON;
import com.tenebrous.jestic.auth.AuthTokenGenerator;
import com.tenebrous.jestic.compents.exception.BizException;
import com.tenebrous.jestic.context.JesticContext;
import com.tenebrous.jestic.context.JesticTask;
import com.tenebrous.jestic.context.Response;
import com.tenebrous.jestic.entity.dto.TokenDto;
import com.tenebrous.jestic.entity.model.request.JesticAuthorityRequest;
import com.tenebrous.jestic.entity.model.request.ServerHearBeatRequest;
import com.tenebrous.jestic.entity.model.response.JesticAuthorityResponse;
import com.tenebrous.jestic.entity.model.response.ServerHearBeatResponse;
import com.tenebrous.jestic.enums.TaskStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Project: jestic-spring-boot
 * @Package: com.zy.tenebrous.jestic.chain
 * @Author: zhangya
 * @CreateTime: 2023-06-28  18:15
 * @Version: 1.0.0
 */
@Slf4j
@Service("JesticHeartBeatVerificationHandler")
public class JesticHeartBeatVerificationHandler extends AbstractJesticChainHandler<ServerHearBeatRequest, ServerHearBeatResponse> {

    private final AuthTokenGenerator authTokenGenerator;

    public JesticHeartBeatVerificationHandler(AuthTokenGenerator authTokenGenerator) {
        this.authTokenGenerator = authTokenGenerator;
    }

    private  int order;

    @Override
    public void handler(JesticContext<? extends JesticTask, ? extends Response> context) {

        ServerHearBeatRequest request = (ServerHearBeatRequest) context.getRequest();
        log.info("JesticHeartBeatVerificationHandler.handler.start.request[{}]", JSON.toJSONString(request));
        ServerHearBeatResponse response = (ServerHearBeatResponse) context.getResponse();
        String token = request.getToken();
        String instanceId = request.getInstanceId();
        // 校验token
        TokenDto tokenDto = authTokenGenerator.checkToken(instanceId, token);
        if (!tokenDto.isToken()) {
            response.setCode(500);
            response.setMessage(tokenDto.getMessage());
            response.setResult(tokenDto.isToken());
            return;
        }
        if (null != nextHandler) {
            nextHandler.handler(context);
        }
    }

    @Override
    public int order(String taskType) {
        return this.order;
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    @Override
    public AbstractJesticChainHandler<ServerHearBeatRequest, ServerHearBeatResponse> setOrder(int order) {
        return null;
    }


}
